from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from utils.webSocket import wbs
import json

custser_router = APIRouter(prefix="/api/customer-service", tags=["在线客服"])


@custser_router.websocket("/ws/{client_id}")
async def customer_service_websocket(websocket: WebSocket, client_id: str):
    """
    客服 WebSocket 连接端点
    
    客户端连接示例：
    ws://localhost:8000/api/customer-service/ws/user_123
    或
    ws://localhost:8000/api/customer-service/ws/admin_456
    """
    print(f"\n{'='*50}")
    print(f"🔵 收到 WebSocket 连接请求")
    print(f"   client_id: {client_id}")
    print(f"   websocket: {websocket}")
    print(f"   路径: {websocket.url.path if hasattr(websocket, 'url') else 'N/A'}")
    print(f"{'='*50}\n")
    
    try:
        print(f"🔷 开始调用 wbs.connect()...")
        await wbs.connect(websocket, client_id)
        print(f"✅ wbs.connect() 成功返回")
    except Exception as e:
        print(f"\n{'!'*50}")
        print(f"❌ WebSocket 连接失败: client_id={client_id}")
        print(f"   错误类型: {type(e).__name__}")
        print(f"   错误信息: {e}")
        print(f"{'!'*50}\n")
        import traceback
        traceback.print_exc()
        raise
    
    try:
        # 发送欢迎消息
        welcome_msg = {
            "type": "system",
            "message": f"欢迎 {client_id}，您已成功连接到客服系统！",
            "timestamp": str(wbs.active_connections)
        }
        await websocket.send_text(json.dumps(welcome_msg, ensure_ascii=False))
        
        # 持续监听客户端消息
        while True:
            # 接收消息
            data = await websocket.receive_text()
            
            try:
                # 解析消息
                message_data = json.loads(data)
                msg_type = message_data.get("type", "text")
                target = message_data.get("target")  # 目标客户端ID
                content = message_data.get("content", data)
                
                print(f"📨 收到来自 {client_id} 的消息: {message_data}")
                
                # 根据消息类型处理
                if msg_type == "direct" and target:
                    # 管理员回复用户 - 通过 Redis 转发到业务端
                    response = {
                        "type": "admin_to_user",
                        "target": target,
                        "from": client_id,
                        "content": content,
                        "timestamp": message_data.get("timestamp")
                    }
                    # 通过 Redis 发送到业务端
                    await wbs.publish_to_redis(
                        message_type="admin_to_user",
                        target_client=target,
                        content=response
                    )
                    print(f"📤 [管理端] 已将管理员 {client_id} 的消息转发给用户 {target}")
                    
                elif msg_type == "broadcast":
                    # 广播消息
                    response = {
                        "type": "broadcast",
                        "from": client_id,
                        "content": content,
                        "timestamp": message_data.get("timestamp")
                    }
                    await wbs.broadcast(response)
                    
                else:
                    # 默认回显消息
                    echo_msg = {
                        "type": "echo",
                        "message": f"服务器收到您的消息: {content}"
                    }
                    await websocket.send_text(json.dumps(echo_msg, ensure_ascii=False))
                    
            except json.JSONDecodeError:
                # 如果不是 JSON 格式，直接回显
                await websocket.send_text(f"Echo: {data}")
                
    except WebSocketDisconnect:
        print(f"🔌 客户端 {client_id} 主动断开连接")
        wbs.disconnect(websocket, client_id)
    except Exception as e:
        print(f"❌ WebSocket 错误 ({client_id}): {str(e)}")
        wbs.disconnect(websocket, client_id)


@custser_router.get("/online-clients")
async def get_online_clients():
    """获取当前在线的客户端列表"""
    online_clients = await wbs.get_online_clients()
    return {
        "success": True,
        "online_count": len(online_clients),
        "clients": online_clients
    }


@custser_router.post("/send-message")
async def send_message_to_client(client_id: str, message: dict):
    """
    通过 HTTP API 发送消息到指定客户端
    
    示例请求：
    POST /api/customer-service/send-message?client_id=user_123
    {
        "type": "notification",
        "content": "您有新的消息"
    }
    """
    try:
        await wbs.send_to_client(client_id, message)
        return {
            "success": True,
            "message": f"消息已发送给 {client_id}"
        }
    except Exception as e:
        return {
            "success": False,
            "error": str(e)
        }
